package com.imxiaoyu.wifi.adb.utils;

import com.google.gson.Gson;

import javax.swing.*;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SettingsUtils {
    private static Gson gson = new Gson();
    private static final String SETTINGS_PATH = "D://wifi-adb-settings.txt";//用于保存数据的txt文件的目录


    /**
     * 获取当前链接的设备的设备列表
     *
     * @return
     */
    public static List<Map<String, Object>> getAllDevice() {
        List<Map<String, Object>> deviceList = new ArrayList<>();
        SettingsEntity entity = getSettings();
        String cmd = entity.getWifiAdbPath() + "/adb.exe " + "devices -l";//获取列表的命令
        List<String> cmdList = CmdUtils.runCmd(cmd);

        //运行adb.exe devices -l 这个命令之后，从返回的结果中解析出设备的相关信息

        for (int i = 1; i < cmdList.size(); i++) {
            //跳过第一行
            Pattern p = Pattern.compile("\\s+");
            Matcher m = p.matcher(cmdList.get(i));
            String str = m.replaceAll(" ");//将多个连续的空格只保留一个
            str = str.replace(":", " ");//将冒号抓换成空格，方便解析
            if (str.indexOf(".") > -1) {
                //如果包含有小数点，证明名字是带端口的，这时候需要把第一个空格还原为冒号
                str = str.replaceFirst(" ", ":");
            }
            System.out.print("\n解析前：" + str);

            Map<String, Object> map = new HashMap<>();
            String[] list = str.split(" ");
            map.put("name", list[0]);
            map.put("device_product", list[3]);
            map.put("model", list[5]);
            map.put("device", list[7]);
            map.put("transport_id", list[9]);
            deviceList.add(map);
        }

        return deviceList;
    }

    /**
     * 将一个已连接的设备保存起来
     *
     * @param map
     */
    public static void saveDevice(Map<String, Object> map) {

        if (isHaveDevice(map)) {
            JOptionPane.showMessageDialog(null, "设备已存在", "保存失败", JOptionPane.ERROR_MESSAGE);
            return;
        }

        SettingsEntity entity = getSettings();
        map.put("id", UUID.randomUUID().toString());//保存的时候给加一个唯一id，方便删除
        entity.getPhoneList().add(map);
        setSettings(entity);
        //保存成功
    }

    /**
     * 根据id，删除一个已保存的设备
     *
     * @param id
     */
    public static void removeDevice(String id) {
        SettingsEntity entity = getSettings();
        List<Map<String, Object>> list = getSettings().getPhoneList();

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).get("id").equals(id)) {
                list.remove(i);
            }
            entity.setPhoneList(list);
            setSettings(entity);
            return;
        }
        //删除成功
    }


    /**
     * 判定一个设备是否已经存在
     *
     * @param map
     * @return
     */
    public static boolean isHaveDevice(Map<String, Object> map) {

        List<Map<String, Object>> deviceList = getSettings().getPhoneList();
        if (deviceList == null) {
            deviceList = new ArrayList<>();
        }
        boolean isHave = false;//是否存在
        for (int i = 0; i < deviceList.size(); i++) {
            if (deviceList.get(i).get("name").equals(map.get("name")) && deviceList.get(i).get("model").equals(map.get("model"))) {
                isHave = true;//这个设备已存在
            }
        }
        return isHave;
    }


    /**
     * 获取保存的数据
     *
     * @return
     */
    public static SettingsEntity getSettings() {
        SettingsEntity settingsEntity;
        String str = readString();
        settingsEntity = gson.fromJson(str, SettingsEntity.class);
        if (settingsEntity == null) {
            settingsEntity = new SettingsEntity();
        }
        return settingsEntity;
    }

    /**
     * 写入保存数据
     *
     * @param entity
     */
    public static void setSettings(SettingsEntity entity) {
        writeString(gson.toJson(entity));
    }

    /**
     * 从文件中读取保存数据的json字符串
     *
     * @return
     */
    private static String readString() {

        File file = new File(SETTINGS_PATH);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try (FileReader reader = new FileReader(SETTINGS_PATH);
             BufferedReader br = new BufferedReader(reader) // 建立一个对象，它把文件内容转成计算机能读懂的语言
        ) {
            String allStr = "";
            String line;
            //网友推荐更加简洁的写法
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
//                System.out.println(line);
                allStr += line;
            }
            return allStr;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json字符串写入到txt文件中
     *
     * @param settingsStr
     */
    private static void writeString(String settingsStr) {
        try {
            File writeName = new File(SETTINGS_PATH); // 相对路径，如果没有则要建立一个新的output.txt文件
            writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
            try (FileWriter writer = new FileWriter(writeName);
                 BufferedWriter out = new BufferedWriter(writer)
            ) {
                out.write(settingsStr); // \r\n即为换行
                out.flush(); // 把缓存区内容压入文件
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
